<script setup>
import { inject, reactive } from 'vue';
import { Toast } from 'vant';
import { upload } from '../uploader';
let props = defineProps({
    control: Object,
    model: Object,
})
let uploadOptions = inject('uploadOptions');
let header = uploadOptions.getHeaders();
let data = reactive({
    fileList: []
})

if (props.model) {
    data.fileList = filesToList(props.model[props.control.id]);
}


function beforeRead(file) {
    if (props.control.props.size > 0) {
        let maxSize = props.control.props.size;
        if (props.control.props.sizeUnit == 'KB') {
            maxSize = 1024 * maxSize;
        } else if (props.control.props.sizeUnit == 'MB') {
            maxSize = 1024 * 1024 * maxSize;
        } else if (props.control.props.sizeUnit == 'GB') {
            maxSize = 1024 * 1024 * 1024 * maxSize;
        }
        if (file.size > maxSize) {
            Toast("最大可以上传" + props.control.props.size + props.control.props.sizeUnit + "的文件");
            return false;
        }
    }
    return true;
}
function afterRead(file) {

    upload(uploadOptions.action, header, file.file).then(res => {
        let fileInfo = uploadOptions.getFileHook(res, file, data.fileList);
        if (fileInfo.url) {
            file.url = fileInfo.url;
            props.model[props.control.id] = data.fileList.map(x => x.url);
        } else {
            Toast(fileInfo);
        }
    }).catch(errMsg => {
        Toast(errMsg || 'getFileHook函数出错了');
    })
}
function beforeDelete(file) {
    props.model[props.control.id].splice(props.model[props.control.id].indexOf(file.url), 1);
    return true;
}

function filesToList(files) {
    if (files) {
        // console.log(files);
        return files.filter(x => x).map((x) => {
            return {
                // name: x.substr(x.lastIndexOf('/') + 1),
                url: x
            }
        });
    }
    return [];
}


</script>

<template>
    <van-field
        :name="control.id"
        :label="control.props.label"
        :rules="control.rules"
        :required="control.rules[0].required"
    >
        <template #input>
            <van-uploader
                v-model="data.fileList"
                :before-read="beforeRead"
                :after-read="afterRead"
                :before-delete="beforeDelete"
                :multiple="control.props.multiple"
                :max-count="control.props.limit"
                :accept="control.props.accept"
                :disabled="control.props.disabled"
                :upload-text="control.props.tip"
            >
                <van-button icon="plus" type="primary">上传文件</van-button>
            </van-uploader>
        </template>
    </van-field>
</template>

